package demo.controller;

import demo.controller.form.NewTestForm;
import demo.controller.form.TestForm;
import demo.enums.TypeEnum;
import demo.error.SysError;
import demo.exception.BizAssert;
import demo.model.result.Response2Result;
import demo.util.enums.EnumUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author meilin.huang
 * @date 2022-02-16 3:36 PM
 */
@Slf4j
@Response2Result
@RestController
@RequestMapping("/demo/")
public class DemoController {

    @GetMapping("biz-assert")
    public void testNotEmpty(@RequestParam(value = "id", required = false) Integer id,
                             @RequestParam(value = "type", required = false) Integer type) {
        BizAssert.notNull(id, "id不能为空");
        BizAssert.equals(id, 1, SysError.MENU_ERROR);
        BizAssert.equals(type, 1, SysError.TYPE_ERROR, type);
    }

    @ApiOperation("原始方式显示枚举描述")
    @PostMapping("test-swagger-enum")
    public void testSwaggerEnumName(@RequestBody TestForm form) {
        log.info(form.toString());
    }

    @ApiOperation("新方式显示枚举描述")
    @PostMapping("test-swagger-enum-new")
    public void testSwaggerEnumNameNew(@RequestBody NewTestForm form) {
        log.info(form.toString());
    }

    @ApiOperation("新方式显示枚举描述-get方法")
    @GetMapping("test-swagger-enum-new-get")
    public void testSwaggerEnumNameNewGet(NewTestForm form) {
        log.info(form.toString());
    }

    @ApiOperation("传统方式校验枚举值合法性")
    @PostMapping("test-check-enum")
    public void testCheckEnum(@RequestBody NewTestForm form) {
        // 校验Integer类型的type字段值为合法枚举值
        BizAssert.isTrue(EnumUtils.isExist(TypeEnum.values(), form.getType()), "type枚举值错误");

        TypeEnum typeEnum = form.getTypeEnum();
        // 校验枚举类型的typeEnum字段需为T1和T2类型
        BizAssert.isTrue(TypeEnum.T1.equals(typeEnum) || TypeEnum.T2.equals(typeEnum), "typeEnum字段枚举值错误");

        log.info(form.toString());
    }

    @ApiOperation("基于注解的方式校验枚举值合法性")
    @PostMapping("test-enum-value")
    public void testEnumValue(@Valid @RequestBody NewTestForm form) {
        log.info(form.toString());
    }
}
